<!--
 * @Author: ChunLai
 * @Date: 2023-08-03 11:08:33
 * @LastEditTime: 2025-09-08 14:15:17
 * @Description: 单张图上传
 * @FilePath: \02.bldinsure\src\views\upload\components\uploadFileBox.vue
-->
<template>
  <div class="upItem">
    <van-uploader :max-count="1" :deletable="false" :after-read="afterRead">
      <div class="upBox">
        <div class="content-img-far">
          <img :src="imgUrl" class="content-img" v-if="imgUrl" />
          <img
            :src="getBgDefault(imgType, target)"
            class="content-img"
            v-else
          />
        </div>
        <div
          class="tips"
          :class="
            ['9', '10', '11', '12', '22'].includes(this.imgType) ? 'css2' : ''
          "
        >
          {{ imgTips }}
        </div>
      </div>
    </van-uploader>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
export default {
  props: {
    /**文件类型 */
    type: "",
    /** 图片类型 */
    imgType: "",
    userId: "", //仅证件需要
    imgSrc: {
      type: [String, Array],
      default: () => "",
    },
    target: {
      default: () => {
        return {
          idType: "",
          uname: "", //投保人，被保人，受益人姓名
          idNum: "",
        };
      },
    },
  },
  computed: {
    ...mapGetters({
      noneOcrCheckIdCard: "dictionary/noneOcrCheckIdCard",
    }),
    imgTips() {
      let msg = "请上传图片";
      let target = this.target;
      const uname = `${target.name || "上传"}`;
      if (this.imgType == "5") {
        msg = `${uname} 证件正面`;
        if (this.target.idType == "0") {
          msg = `${uname} 身份证人像面`;
        } else if (this.target.idType == "3") {
          msg = `${uname} 户口本本人页`;
        }
      } else if (this.imgType == "6") {
        msg = `${uname} 证件背面`;
        if (this.target.idType == "0") {
          msg = `${uname} 身份证国徽面`;
        } else if (this.target.idType == "3") {
          msg = `${uname} 户口本户主页`;
        }
      } else if (this.imgType == "7") {
        msg = "银行卡（带卡号一面）";
      } else if (this.imgType == "9") {
        msg = "客户已签字的《人身保险投保提示书》第一页";
      } else if (this.imgType == "10") {
        msg = "客户已签字的《人身保险投保提示书》第二页";
      } else if (this.imgType == "22") {
        msg = "客户已签字的《人身保险投保提示书》第三页";
      } else if (this.imgType == "11") {
        msg = "客户签字时的照片";
      } else if (this.imgType == "12") {
        msg = "客户手持已签字的《人身保险投保提示书》正面照";
      } else if (this.imgType == "20") {
        msg = "营业执照";
      } else if (this.imgType == "21") {
        msg = "执业资格证";
      }
      return msg;
    },
    needOcrAuth() {
      //  1.判断配置是否需要OCR   2.imgType 7 银行卡  3.imgType 5,6, 且为身份证
      let res = false;
      if (!this.noneOcrCheckIdCard) {
        const chk1 = this.imgType == "7",
          chk2 =
            ["5", "6"].includes(this.imgType) &&
            this.target.idType &&
            this.target.idType == "0";
        if (chk1 || chk2) {
          res = true;
        }
      }
      return res;
    },
  },
  filters: {},
  data() {
    return {
      imgUrl: "",
      ocr_flag: "", //证件，银行卡 ocrFlag，未识别不传，识别失败传0，识别成功传1
    };
  },
  watch: {
    imgSrc(val) {
      // console.log(val);
      this.imgUrl = val;
    },
  },
  mounted() {
    this.$nextTick(() => {
      if (this.imgSrc) {
        this.imgUrl = this.imgSrc || "";
      }
    });
  },
  methods: {
    getBgDefault(type, target) {
      let picName = "";
      if (type === "7") {
        picName = "eg_bank";
      } else if (type == "5") {
        if (target.idType === "0") {
          picName = "eg_sfz1";
        } else if (target.idType === "3") {
          picName = "eg_hkb_1";
        } else {
          picName = "eg_common";
        }
      } else if (type == "6") {
        if (target.idType === "0") {
          picName = "eg_sfz2";
        } else if (target.idType === "3") {
          picName = "eg_hkb_2";
        } else {
          picName = "eg_common";
        }
      } else if (type == "9") {
        picName = "zb1";
      } else if (type == "10") {
        picName = "zb2";
      } else if (type == "11") {
        picName = "zb3";
      } else if (type == "12") {
        picName = "zb4";
      } else {
        picName = "eg_common";
      }
      return `${this.imgUrlPath}/img/${picName}.png`;
    },
    /**压缩上传图片 */
    afterRead(file) {
      if (file.file.size > 204800) {
        let canvas = document.createElement("canvas");
        let context = canvas.getContext("2d");
        let img = new Image();
        img.src = file.content;
        img.onload = () => {
          const whRatio = img.width / img.height;
          const nw = 750;
          const nh = Math.ceil(nw / whRatio);
          canvas.width = nw;
          canvas.height = nh;
          context.drawImage(img, 0, 0, nw, nh);
          file.content = canvas.toDataURL(file.file.type, 0.92);
          this.getImgOssUrl(file.content);
        };
      } else {
        this.getImgOssUrl(file.content);
      }
    },
    /**获取OSS图片地址 */
    getImgOssUrl(imgBase) {
      let pic_base64 = imgBase
        .replace(new RegExp("image/jpeg", ""), "image/jpg")
        .replace(new RegExp("image/png", ""), "image/jpg");
      this.$store.commit("updateLoadTxt", "正在上传，请稍后");
      this.$store.dispatch("apis/fileAdminUpload", pic_base64).then((res) => {
        let picUrl = res.url;
        if (!res.url && res.data) {
          picUrl = res.data.cospath;
        }
        //   判断是否需要识别
        if (this.needOcrAuth) {
          this.checkOcrInfo(picUrl);
        } else {
          this.saveImgInfo(picUrl);
        }
      });
    },
    /** 识别图片 */
    checkOcrInfo(picUrl) {
      // 只有身份证和银行卡需要
      this.$store.commit("updateLoad", true);
      this.$store.commit("updateLoadTxt", "证件识别中");
      let params = {
        ...this.apiComParams,
        name: this.target.name || "",
        idNo: this.target.idNum || "",
        imageUrl: picUrl,
      };
      this.$http
        .post(`/ms-insure/api/common/idcardAuthentication`, params, {
          json: true,
        })
        .then(({ data }) => {
          this.$store.commit("updateLoadTxt", "信息比对中");
          this.ocInfoHandle(data.data, picUrl);
        })
        .catch(() => {
          this.$store.commit("updateLoad", false);
          this.$baseConfirm(
            `系统未能识别出身份证或银行卡，如继续上传，会导致问题件产生。是继续上传?`,
            () => {
              this.saveImgInfo(picUrl, "0");
            },
            null,
            "继续上传",
            "重新上传"
          );
        });
    },
    /** OCR信息比对 */
    ocInfoHandle(certiMsg, imgUrl) {
      let _this = this;
      let isPass = true;
      if (this.apicType === "bank") {
        // 银行卡
        isPass =
          this.comparisonMsg.bankAccNo !== certiMsg.cardNumber ? false : isPass;
      } else {
        if (this.certiModule === "face") {
          // iDNumber校验
          const compaIdNum =
              this.comparisonMsg.idNum !== certiMsg.frontResult.iDNumber,
            compaName = this.comparisonMsg.name !== certiMsg.frontResult.name;
          isPass = compaIdNum || compaName ? false : isPass;
        } else if (this.certiModule === "back") {
          // 有效期校验
          const dateStr = certiMsg.backResult.endDate;
          let dateVal2 =
            dateStr !== "长期"
              ? `${dateStr.substr(0, 4)}-${dateStr.substr(
                  4,
                  2
                )}-${dateStr.substr(6, 2)}`
              : "长期";
          console.log("有效期止期:", dateVal2);
          isPass =
            this.comparisonMsg.validDateEnd !== dateVal2 ? false : isPass;
        }
      }
      this.$store.commit("updateLoad", false);
      this.$store.commit("updateLoadTxt", "数据加载中");
      // console.log("3---", isPass)
      if (!isPass) {
        this.$baseConfirm(
          "OCR识别信息和填写的不一致,如继续上传，会导致问题件产生。是否继续投保?",
          () => {
            this.saveImgInfo(imgUrl, "0");
          },
          null,
          "继续投保",
          "重新上传"
        );
      } else {
        this.saveImgInfo(imgUrl, "1");
      }
    },
    /**保存图片 */
    saveImgInfo(picUrl, ocr_flag = "") {
      let params = {
        ...this.apiComParams,
        type: this.type,
        imgType: this.imgType,
        imgUrl: picUrl,
        idNum: this.target.idNum || "",
        ocrFlag: ocr_flag,
      };
      this.$store
        .dispatch("apis/comAdminApiRequest", {
          apiParams: params,
          apiName: "saveImg",
        })
        .then((res) => {
          this.imgUrl = picUrl;
        });
    },
  },
};
</script>

<style lang="less">
.upItem {
  // flex: 1;
  width: 50%;
  padding: 0 5px;
  display: flex;
  flex-wrap: wrap;
  margin-top: 10px;

  .van-uploader__upload {
    width: 80px;
    height: 80px;
    background-color: #f2f2f2;
  }

  .van-uploader {
    width: 100%;
  }
}

.upBox {
  background: #f4f8fe;
  border-radius: 10px;
}

.tips {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  color: #ffffff;
  padding: 8px 12px;
  width: 100%;
  border-radius: 0px 0px 10px 10px;
  background-color: #6699ff;

  &.css2 {
    color: #747474;
    padding: 8px 0;
    background-color: #fff;
  }
}

.content-img-far {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100px;
  border-radius: 8px;
  overflow: hidden;
  padding: 10px;

  .content-img {
    height: 100%;
  }
}

.tick_img {
  width: 16px;
  height: 16px;
  border-radius: 50%;
  margin-right: 5px;
}

p {
  margin: 0;
}

.viewBox {
  display: flex;
  flex-wrap: wrap;

  .closeIco {
    position: absolute;
    right: 0;
    top: 0;
  }

  .viewItem {
    margin-right: 10px;
    margin-bottom: 10px;
    position: relative;
  }
}
</style>
